package Cantella::DJabberd::Store::Result::RosterItem;

use base qw/DBIx::Class::Core/;
use metaclass 'Reaction::Meta::Class';
use Moose;

use MooseX::Types::Moose qw/ArrayRef Int/;
use Reaction::Types::Core qw/NonEmptySimpleStr/;

use aliased 'Cantella::DJabberd::Store::Result::UserJid';
use aliased 'Cantella::DJabberd::Store::Result::RosterGroupItem' => 'GroupItem';

use namespace::clean -except => [ 'meta' ];

has id           => (is => 'ro', required => 1, isa => Int );
has owner        => (is => 'rw', required => 1, isa => UserJid );
has name         => (is => 'rw', required => 1, isa => NonEmptySimpleStr );
has contact      => (is => 'rw', required => 1, isa => UserJid );
has subscription => (is => 'rw', required => 1, isa => Int );
has roster_groups => (
                      isa => ArrayRef,
                      reader => 'get_roster_groups',
                      writer => 'set_roster_groups'
                     );

{
  no warnings 'redefine';
  *get_roster_groups = sub { [ shift->roster_groups->all ] };
}

__PACKAGE__->table('roster_items');
__PACKAGE__->add_columns
  (
   id           => {
                    data_type => "INT",
                    size => 10,
                    default_value => undef,
                    is_nullable => 0,
                    is_auto_increment => 1,
                    extra => { unsigned => 1 },
                   },
   owner_id     => {
                     data_type => "INT",
                     size => 10,
                     is_nullable => 0,
                     is_foreign_key => 1,
                     extra => { unsigned => 1 },
                   },
   contact_id  => {
                    data_type => "INT",
                    size => 10,
                    is_nullable => 0,
                    is_foreign_key => 1,
                    extra => { unsigned => 1 },
                   },
   name         => {
                    data_type => "VARCHAR",
                    size => 255,
                    is_nullable => 0,
                   },
   subscription => {
                    data_type => "TINYINT",
                    size => 3,
                    is_nullable => 0,
                    extra => { unsigned => 1 },
                   },
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->add_unique_constraint(owner_contact => [qw/owner_id contact_id/]);

__PACKAGE__->belongs_to(owner   => UserJid, { id => 'owner_id' }  );
__PACKAGE__->belongs_to(contact => UserJid, { id => 'contact_id' });

__PACKAGE__->has_many(roster_group_items => GroupItem, {roster_item_id => 'id'});
__PACKAGE__->many_to_many(roster_groups => 'roster_group_items', 'roster_group');

sub display_name { shift->name }

__PACKAGE__->meta->make_immutable(inline_constructor => 0);

1;
